package com.xjt.wx_admin.security;

import com.alibaba.fastjson.JSON;
import com.xjt.wx_admin.exception.NotLoginException;
import com.xjt.wx_admin.util.RedisUtil;
import com.xjt.wx_admin.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil ;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1、从请求头中获取token，如果请求头中不存在token，直接放行即可！由Spring Security的过滤器进行校验！
        String token = request.getHeader("Authorization");
        if(token == null || "".equals(token)) {
            filterChain.doFilter(request , response);
            return ;
        }

        // 2、对token进行解析，取出其中的userId
        String username;
        if (!TokenUtils.verify(token)) {
            request.setAttribute("errorMessage","登录过期!");
            request.setAttribute("code",502);
            throw new NotLoginException("登录过期");
        }else {
            username = TokenUtils.getTokenValue(token, "userName").asString();
        }
        // 3、使用userId从redis中查询对应的LoginUser对象
        String loginUserJson = (String)redisUtil.get("login:" + username+":"+token);
        if (loginUserJson==null){
            request.setAttribute("errorMessage","登录过期!");
            request.setAttribute("code",502);
            throw new NotLoginException("登录过期");
        }
        LoginUser loginUser = JSON.parseObject(loginUserJson, LoginUser.class);
        if(loginUser != null) {
            // 4、然后将查询到的LoginUser对象的相关信息封装到UsernamePasswordAuthenticationToken对象中，然后将该对象存储到Security的上下文对象中
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null , null) ;
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        // 5、放行
        filterChain.doFilter(request , response);
    }

}